# cython: language_level=3
import json

from fastapi import APIRouter, Depends
from sqlalchemy.orm import Session

from app.db.sql.resource import find_or_create_resource
from app.db.sql.resource_history_data import save_data
from app.middlewares.redis import get_redis
from app.schemas.update_resource import UpdateResourceRequest
from common.database import get_db
from common.http import ok_response, error_response
from common.redis import MyRedis

router = APIRouter(tags=["update-resource-data"])
router.prefix = "/device"


@router.post("/updateResourceData")
def update_resource_data(payload: UpdateResourceRequest, db: Session = Depends(get_db),
                         redis: MyRedis = Depends(get_redis)):
    """
    设备数据更新
    """
    resource = find_or_create_resource(db, payload)
    if not resource:
        return error_response(500,None)
    save_data(db, resource.resource_id, payload.data, payload.acquisitionTime)
    redis.set_rtd(resource.resource_id, json.dumps(payload.data))
    return ok_response(None)
